package com.example.demo02.controller.FilesUpload;

import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
@Tag(name = "单文件上传接口")
@RestController
public class FileUploadController {
    @PostMapping("/upload")
    public String upload(@RequestParam("uploadFile") MultipartFile uploadFile, HttpServletRequest request) {
        if (uploadFile == null || uploadFile.isEmpty()) {
            return "空文件";
        }
        // 获取上传目标文件夹的绝对路径（也可以是本地路径）
        String realPath = "D:/IDEA/code/java/demo02/MyFile";
//        String realPath = request.getServletContext().getRealPath("/uploadFile");
        System.out.println("realPath" + realPath); //实际目录
        File parentDir = new File(realPath);
        //如果不存在这个目录则会自动创建文件夹
        if (!parentDir.isDirectory()) {
            parentDir.mkdir();
        }
        String filename = uploadFile.getOriginalFilename();
        File target = new File(parentDir, filename); // 创建上传目标文件
        try {
            // 源文件拷贝到目标文件中
            uploadFile.transferTo(target);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        System.out.println(formatter.format(date));
        return "当前时间" + formatter.format(date) + "单个文件上传成功";
    }
}
